<template>
  <ECharts
    :options="chartOptions"
    height="650px" />
</template>

<script lang="ts" setup>
import { ref, type Ref } from 'vue'
import ECharts from '@/components/Echarts.vue'
import { useExposureLineStore } from '@/stores/exposureLine'
import { IntervalType } from '@/enums/index.ts'
import { completeEndDates } from '@/utils/index.ts'

const exposureLineStore = useExposureLineStore()

// 数据长度不同以长为准
const colors = [
  '#5470C6',
  '#ee6666',
  '#fac858',
  '#73c0de',
  '#ea7ccc',
  '#3ba272',
  '#fc8452',
  '#9a60b4',
  '#91cc75',
]
const keyMap = {
  vn: '曝光数',
  cn: '点击数',
  pn: '购买数',
}

type KeyMapType = keyof typeof keyMap

interface ChartOption {
  color?: string[]
  tooltip?: object
  legend?: object
  grid?: object
  dataZoom: object[]
  xAxis?: {
    type: string
    axisTick: { alignWithLabel: boolean }
    axisLine: { onZero: boolean; lineStyle: { color: string } }
    data: string[]
  }[]
  yAxis?: object[]
  series?: object[]
}

const defaultOption = {
  color: colors,
  toolbox: {
    show: true,
    feature: {
      dataZoom: {
        title: {
          zoom: '区域缩放',
          back: '缩放还原',
        },
      },
      restore: {
        title: '还原',
      },
      saveAsImage: {
        title: '保存为图片',
      },
    },
    right: 0,
    top: -5,
  },
  tooltip: {
    trigger: 'axis',
    position: 'left',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985',
      },
    },
    formatter: (params: any) => {
      // params[0] 日期
      // params[1] 对照日期
      let result = '<div style="text-align: left;">'
      params.forEach((item: any) => {
        result += `
          ${item.marker} ${item.seriesName}:
          ${item.value.toLocaleString('en-US')} <br/>
        `
      })
      if (exposureLineStore.intervalType === IntervalType.DAY) {
        result += `
          <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#5470c6;"></span>
          点击率：${params[0].data.cnRate || 0}%<br/>
          <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#fc8452;"></span>
          购买率：${params[0].data.pnRate || 0}‰<br/>
        `
      } else {
        if (params.length === 1) {
          result += `
            <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#5470c6;"></span>
            点击率${params[0].seriesName.slice(3)}：${params[0].data.cnRate || 0}%<br/>
            <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#fc8452;"></span>
            购买率${params[0].seriesName.slice(3)}：${params[0].data.pnRate || 0}‰<br/>
          `
        } else {
          result += `
            <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#5470c6;"></span>
            点击率${params[0].seriesName.slice(3)}：${params[0].data.cnRate || 0}%<br/>
            <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#91cc75;"></span>
            点击率${params[1].seriesName.slice(3)}：${params[1].data.cnRate || 0}%<br/>
            <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#fc8452;"></span>
            购买率${params[0].seriesName.slice(3)}：${params[0].data.pnRate || 0}‰<br/>
            <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#ea7ccc;"></span>
            购买率${params[1].seriesName.slice(3)}：${params[1].data.pnRate || 0}‰<br/>
          `
        }
      }
      result += '</div>'
      return result
    },
  },
  dataZoom: [
    {
      type: 'slider', // 滑块型
      xAxisIndex: [0, 1],
      start: 0,
      end: 100,
    },
    {
      type: 'inside', // 内置型
      xAxisIndex: [0, 1],
      start: 0,
      end: 100,
    },
  ],
  legend: {
    textStyle: {
      color: '#CFD3DC', // 图例文本颜色
      fontSize: 12,
      fontWeight: 'bold',
    },
  },
  grid: {
    top: 60,
    bottom: 50,
    containLabel: true, // 确保坐标轴标签在 grid 区域内
  },
  xAxis: [],
  yAxis: [
    {
      type: 'value',
      name: '曝光/点击',
      nameGap: 25,
      axisLabel: {
        color: '#CFD3DC',
        fontSize: 12,
        fontWeight: 'bold',
      },
      nameTextStyle: {
        color: '#CFD3DC',
        fontSize: 14,
        fontWeight: 'bold',
        padding: [0, 70, 0, 0],
      },
    },
    {
      type: 'value',
      name: '购买',
      nameGap: 25,
      axisLabel: {
        color: '#CFD3DC',
        fontSize: 12,
        fontWeight: 'bold',
      },
      nameTextStyle: {
        color: '#CFD3DC',
        fontSize: 14,
        fontWeight: 'bold',
        padding: [0, 0, 0, 40],
      },
    },
  ],
  series: [],
}
const chartOptions = ref<ChartOption>(defaultOption) as Ref<ChartOption>

/**
 * 设置图表选项
 */
const setChatOptions = () => {
  if (exposureLineStore.intervalType === IntervalType.DAY) {
    const xAxis = [
      {
        type: 'category',
        axisTick: {
          alignWithLabel: true,
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            color: colors[0],
          },
        },
        data: exposureLineStore.startData.map(elem => elem.date),
      },
    ]
    const series = Object.keys(keyMap)
      .map((key, i) => {
        return [
          {
            name: keyMap[key as KeyMapType],
            type: key === 'pn' ? 'bar' : 'line',
            itemStyle: {
              color: key === 'pn' ? colors[i + 1] : colors[i],
            },
            lineStyle: {
              color: colors[i],
            },
            yAxisIndex: key === 'pn' ? 1 : 0,
            smooth: true,
            data: exposureLineStore.startData.map(elem => {
              return {
                value: elem[key as KeyMapType],
                pnRate: elem.pnRate,
                cnRate: elem.cnRate,
              }
            }),
          },
        ]
      })
      .flat()
    chartOptions.value = {
      ...defaultOption,
      xAxis,
      series,
    }
  } else {
    const series = Object.keys(keyMap)
      .map((key, i) => {
        return [
          {
            name:
              keyMap[key as KeyMapType] +
                exposureLineStore.startData?.[0]?.date?.slice(0, 10) || '',
            type: key === 'pn' ? 'bar' : 'line',
            itemStyle: {
              color: key === 'pn' ? colors[i + 1] : colors[i],
            },
            lineStyle: {
              color: colors[i],
            },
            yAxisIndex: key === 'pn' ? 1 : 0,
            smooth: true,
            data: exposureLineStore.startData.map(elem => {
              return {
                value: elem[key as KeyMapType],
                pnRate: elem.pnRate,
                cnRate: elem.cnRate,
              }
            }),
          },
          {
            name:
              keyMap[key as KeyMapType] +
                exposureLineStore.endData?.[0]?.date?.slice(0, 10) || '',
            type: key === 'pn' ? 'bar' : 'line',
            itemStyle: {
              color: key === 'pn' ? colors[i + 3] : colors[i],
            },
            lineStyle: {
              type: 'dashed',
              color: colors[i],
              opacity: 0.7,
            },
            yAxisIndex: key === 'pn' ? 1 : 0,
            smooth: true, // 折线圆滑
            data: exposureLineStore.endData.map(elem => {
              return {
                value: elem[key as KeyMapType],
                pnRate: elem.pnRate,
                cnRate: elem.cnRate,
              }
            }),
          },
        ]
      })
      .flat()

    const xAxis = completeEndDates(
      exposureLineStore.endData.map(elem => elem.date),
      exposureLineStore.startData.map(elem => elem.date),
    ).map((elem, i) => {
      return {
        type: 'category',
        axisTick: {
          alignWithLabel: true,
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            color: colors[i],
          },
        },
        data: elem,
      }
    })
    chartOptions.value = {
      ...defaultOption,
      xAxis,
      series,
    }
  }
}
defineExpose({
  setChatOptions,
})
</script>
